package com.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.model.CFUser;


@Repository("userDao")
public class UserDaoImpl implements UserDao {
	
	private SessionFactory sessionFactory;
	
	@Autowired
	public UserDaoImpl(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private static final Logger logger = Logger.getLogger(UserDaoImpl.class);
	
	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	
	@Override
	public void addUser(CFUser user) {
		currentSession().save(user);

	}

	@Override
	public void saveUser(CFUser user) {
		currentSession().update(user);
	}

	@Override
	public CFUser findUserByUserName(String username) {
		Query query=currentSession().createQuery("from CFUser where username ='" + username + "'");
		return (CFUser) query.uniqueResult();
	}

	@Override
	public void deleteUser(String username) {
		
		Session session = currentSession();
		Query query = session.createQuery("from CFUser where username = :username");
		query.setString("username", username);
		@SuppressWarnings("unchecked")
		List<CFUser> users = query.list();
		session.delete(users.get(0));		
	}

	@Override
	public boolean isUsernameAvailable(String username) {
		
		Query query = currentSession().createQuery("from CFUser where username = :username");
		query.setString("username", username);
		@SuppressWarnings("unchecked")
		List<CFUser> users = query.list();
		return users.isEmpty() ? true: false;
	}
	
}
